package com.start.pay.core;

import com.start.common.tools.SpringContextTools;
import com.start.common.tools.StartEnumTools;
import com.start.common.tools.StartRedisLockTools;
import com.start.pay.core.entity.StartPayOrderEntity;
import com.start.pay.core.enums.StartPayState;
import com.start.pay.core.event.GlobalStartPayOrderEventDispatcher;
import com.start.pay.core.model.PlatformOrderPayResult;
import com.start.pay.core.service.StartPayOrderService;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 订单核对
 */
public class StartOrderCheckServer {
    private static final StartOrderCheckServer server = new StartOrderCheckServer();
    private static final ExecutorService executorService = Executors.newSingleThreadExecutor();

    private StartPayOrderService startPayOrderService;
    private StartRedisLockTools lockTools;
    private GlobalStartPayOrderEventDispatcher dispatcher;
    private volatile boolean isInit = false;

    private void init() {
        lockTools = SpringContextTools.getBean(StartRedisLockTools.class);
        startPayOrderService = SpringContextTools.getBean(StartPayOrderService.class);
        dispatcher = GlobalStartPayOrderEventDispatcher.getInstance();
    }

    public static StartOrderCheckServer getInstance() {
        if (!server.isInit) {
            synchronized (StartOrderCheckServer.class) {
                if (server.isInit) {
                    return server;
                }
                server.init();
                server.isInit = true;
            }
        }
        return server;
    }

    /**
     * 添加待核对的订单
     *
     * @param orderNo
     */
    public void addOrder(String orderNo) {
        executorService.execute(() -> checkOrder(orderNo));
    }

    public StartPayOrderEntity checkOrder(String orderNo) {
        StartPayOrderEntity order = startPayOrderService.getStartPayOrderByOrderNo(orderNo);
        if (order.getPayState() != 1 && order.getPayState() != -2) {
            return order;
        }
        if (lockTools.hasLock(orderNo)) {
            return order;
        }
        if (lockTools.Lock(orderNo, 1000 * 60L)) {
            try {
                if (order.getPayState() == 1) {
                    handlerPayOrder(order);


                } else if (order.getPayState() == -2) {
                    queryRefundOrder(order);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lockTools.unLocal(orderNo);
            }
        }
        return order;

    }

    /**
     * 查询订单是否支付成功
     *
     * @param order
     */
    private void handlerPayOrder(StartPayOrderEntity order) {
        PlatformOrderPayResult platformOrderPayResult = StartPayServerService.getInstance().queryPayPlatform(order);
        if (!platformOrderPayResult.isQueryState()) {
            return;
        }
        StartPayState payState = StartEnumTools.findEnumByValue(StartPayState.class, platformOrderPayResult.getPayState());
        if (payState != StartPayState.PAY_SUCCESS) {
            return;
        }
        order.setPayState(StartPayState.PAY_SUCCESS.getValue());
        startPayOrderService.updateById(order);
        dispatcher.onPayOrderSuccess(order);
    }

    /**
     * 查询订单是否退款成功
     *
     * @param order
     */
    private void queryRefundOrder(StartPayOrderEntity order) {
        PlatformOrderPayResult platformOrderPayResult = StartPayServerService.getInstance().queryRefundOrderPlatform(order);
        if (!platformOrderPayResult.isQueryState()) {
            return;
        }

        StartPayState payState = StartEnumTools.findEnumByValue(StartPayState.class, platformOrderPayResult.getPayState());
        if (payState != StartPayState.PAY_REFUND_SUCCESS) {
            return;
        }
        order.setPayState(StartPayState.PAY_REFUND_SUCCESS.getValue());
        startPayOrderService.updateById(order);
        dispatcher.onOrderRefundSuccess(order);
    }


}
